<template>
  <div class="outbound-prediction-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>出库数量智能预测</h2>
      <p class="subtitle">基于ML.NET机器学习的动态库存预测系统</p>
    </div>

    <!-- 预测配置区域 -->
    <el-card class="prediction-config" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>预测配置</span>
          <el-button type="primary" @click="startPrediction" :loading="predicting">
            开始预测
          </el-button>
        </div>
      </template>
      
      <el-form :model="predictionConfig" label-width="120px" class="config-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="预测周期">
              <el-select v-model="predictionConfig.predictionPeriod" placeholder="选择预测周期">
                <el-option label="未来1周" value="1w" />
                <el-option label="未来1个月" value="1m" />
                <el-option label="未来3个月" value="3m" />
                <el-option label="未来6个月" value="6m" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预测模型">
              <el-select v-model="predictionConfig.modelType" placeholder="选择预测模型">
                <el-option label="线性回归" value="linear" />
                <el-option label="时间序列" value="timeseries" />
                <el-option label="随机森林" value="randomforest" />
                <el-option label="神经网络" value="neural" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="置信区间">
              <el-select v-model="predictionConfig.confidenceLevel" placeholder="选择置信区间">
                <el-option label="90%" value="0.9" />
                <el-option label="95%" value="0.95" />
                <el-option label="99%" value="0.99" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="产品类别">
              <el-select v-model="predictionConfig.categoryId" placeholder="选择产品类别" clearable>
                <el-option 
                  v-for="category in categories" 
                  :key="category.id" 
                  :label="category.name" 
                  :value="category.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库">
              <el-select v-model="predictionConfig.depotId" placeholder="选择仓库" clearable>
                <el-option 
                  v-for="depot in depots" 
                  :key="depot.id" 
                  :label="depot.name" 
                  :value="depot.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="历史数据范围">
              <el-select v-model="predictionConfig.historyRange" placeholder="选择历史数据范围">
                <el-option label="最近3个月" value="3m" />
                <el-option label="最近6个月" value="6m" />
                <el-option label="最近12个月" value="12m" />
                <el-option label="最近24个月" value="24m" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 预测结果展示 -->
    <el-card class="prediction-results" shadow="hover" v-if="predictionResults.length > 0">
      <template #header>
        <div class="card-header">
          <span>预测结果</span>
          <div class="header-actions">
            <el-button type="success" @click="exportResults">导出结果</el-button>
            <el-button @click="refreshResults">刷新</el-button>
          </div>
        </div>
      </template>

      <!-- 预测统计卡片 -->
      <div class="prediction-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-number">{{ totalPredictedQuantity }}</div>
              <div class="stat-label">预测总出库量</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-number">{{ averagePredictedQuantity }}</div>
              <div class="stat-label">平均预测出库量</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-number">{{ predictionAccuracy }}%</div>
              <div class="stat-label">预测准确率</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-number">{{ riskLevel }}</div>
              <div class="stat-label">库存风险等级</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 预测图表 -->
      <div class="prediction-charts">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-container">
              <h4>出库量趋势预测</h4>
              <v-chart class="chart" :option="trendChartOption" :autoresize="true" />
            </div>
          </el-col>
          <el-col :span="12">
            <div class="chart-container">
              <h4>产品出库量分布</h4>
              <v-chart class="chart" :option="distributionChartOption" :autoresize="true" />
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 预测详情表格 -->
      <div class="prediction-table">
        <h4>详细预测数据</h4>
        <el-table :data="predictionResults" border style="width: 100%">
          <el-table-column prop="productCode" label="产品编码" width="120" />
          <el-table-column prop="productName" label="产品名称" width="200" />
          <el-table-column prop="categoryName" label="产品类别" width="120" />
          <el-table-column prop="currentStock" label="当前库存" width="100" />
          <el-table-column prop="predictedQuantity" label="预测出库量" width="120" />
          <el-table-column prop="confidence" label="置信度" width="100">
            <template #default="scope">
              <el-progress 
                :percentage="scope.row.confidence" 
                :color="getConfidenceColor(scope.row.confidence)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="riskLevel" label="风险等级" width="100">
            <template #default="scope">
              <el-tag :type="getRiskLevelType(scope.row.riskLevel)">
                {{ scope.row.riskLevel }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="recommendation" label="建议" width="200" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="primary" size="small" @click="viewDetails(scope.row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 数据质量检查 -->
    <el-card class="data-quality" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>数据质量检查</span>
          <el-button type="warning" @click="checkDataQuality">检查数据质量</el-button>
        </div>
      </template>

      <el-alert
        v-if="dataQualityIssues.length > 0"
        title="发现数据质量问题"
        type="warning"
        :closable="false"
        show-icon
      >
        <template #default>
          <ul>
            <li v-for="issue in dataQualityIssues" :key="issue.id">
              {{ issue.description }}
            </li>
          </ul>
        </template>
      </el-alert>

      <div v-else class="quality-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="quality-item">
              <div class="quality-number">{{ dataQuality.completeness }}%</div>
              <div class="quality-label">数据完整性</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="quality-item">
              <div class="quality-number">{{ dataQuality.accuracy }}%</div>
              <div class="quality-label">数据准确性</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="quality-item">
              <div class="quality-number">{{ dataQuality.consistency }}%</div>
              <div class="quality-label">数据一致性</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="quality-item">
              <div class="quality-number">{{ dataQuality.timeliness }}%</div>
              <div class="quality-label">数据时效性</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import http from '@/http/axiosHelper'
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import axios from 'axios'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 预测配置
const predictionConfig = reactive({
  predictionPeriod: '1m',
  modelType: 'timeseries',
  confidenceLevel: '0.95',
  categoryId: '',
  depotId: '',
  historyRange: '12m'
})

// 预测结果
const predictionResults = ref([])
const predicting = ref(false)

// 统计数据
const totalPredictedQuantity = ref(0)
const averagePredictedQuantity = ref(0)
const predictionAccuracy = ref(0)
const riskLevel = ref('低')

// 数据质量
const dataQuality = reactive({
  completeness: 95,
  accuracy: 92,
  consistency: 88,
  timeliness: 96
})

interface DataQualityIssue {
  id: number
  description: string
  severity: string
  count: number
}

const dataQualityIssues = ref<DataQualityIssue[]>([])

// 模拟数据
const categories = ref([
  { id: 1, name: '饮品' },
  { id: 2, name: '电子产品' },
  { id: 3, name: '服装' },
  { id: 4, name: '文具' },
  { id: 5, name: '家居' }
])

const depots = ref([
  { id: 1, name: '仓库一' },
  { id: 2, name: '仓库二' },
  { id: 3, name: '仓库三' },
  { id: 4, name: '仓库四' }
])

// 图表配置
const trendChartOption = computed(() => ({
  title: {
    text: '出库量趋势预测',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['历史出库量', '预测出库量', '置信区间'],
    bottom: 10
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '历史出库量',
      type: 'line',
      data: [120, 132, 101, 134, 90, 230],
      smooth: true
    },
    {
      name: '预测出库量',
      type: 'line',
      data: [null, null, null, 140, 160, 180],
      smooth: true,
      lineStyle: {
        type: 'dashed'
      }
    }
  ]
}))

const distributionChartOption = computed(() => ({
  title: {
    text: '产品出库量分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  series: [
    {
      type: 'pie',
      radius: '50%',
      data: [
        { value: 335, name: '饮品' },
        { value: 310, name: '电子产品' },
        { value: 234, name: '服装' },
        { value: 135, name: '文具' },
        { value: 1548, name: '家居' }
      ]
    }
  ]
}))

// 开始预测
const startPrediction = async () => {
  predicting.value = true
  try {
    // 构建预测请求数据
    const requestData = {
      predictionConfig,
      historicalData: await getHistoricalData(),
      currentStockData: await getCurrentStockData()
    }

    // 调用ML.NET预测API
    const response = await axios.post('/api/MLNet/PredictOutbound', requestData)
    
    if (response.data.code === 200) {
      predictionResults.value = response.data.data.predictions
      updatePredictionStats(response.data.data)
      ElMessage.success('预测完成！')
    } else {
      ElMessage.error(response.data.message || '预测失败')
    }
  } catch (error) {
    console.error('预测失败:', error)
    ElMessage.error('预测过程中发生错误')
  } finally {
    predicting.value = false
  }
}

// 获取历史数据
const getHistoricalData = async () => {
  try {
    const response = await axios.get('/api/Ledger/ShowEnterOut', {
      params: {
        businessType: 2, // 出库
        pageSize: 1000,
        historyRange: predictionConfig.historyRange
      }
    })
    return response.data.items || []
  } catch (error) {
    console.error('获取历史数据失败:', error)
    return []
  }
}

// 获取当前库存数据
const getCurrentStockData = async () => {
  try {
    const response = await axios.get('/api/Ledger/ShowStock', {
      params: {
        pageSize: 1000
      }
    })
    return response.data.items || []
  } catch (error) {
    console.error('获取库存数据失败:', error)
    return []
  }
}

// 更新预测统计
const updatePredictionStats = (data: any) => {
  totalPredictedQuantity.value = data.totalPredictedQuantity || 0
  averagePredictedQuantity.value = data.averagePredictedQuantity || 0
  predictionAccuracy.value = data.accuracy || 0
  riskLevel.value = data.riskLevel || '低'
}

// 检查数据质量
const checkDataQuality = async () => {
  try {
    const response = await axios.get('/api/MLNet/CheckDataQuality')
    if (response.data.code === 200) {
      Object.assign(dataQuality, response.data.data.quality)
      dataQualityIssues.value = response.data.data.issues || []
      ElMessage.success('数据质量检查完成')
    }
  } catch (error) {
    console.error('数据质量检查失败:', error)
    ElMessage.error('数据质量检查失败')
  }
}

// 导出结果
const exportResults = () => {
  ElMessage.success('预测结果导出功能开发中...')
}

// 刷新结果
const refreshResults = () => {
  if (predictionResults.value.length > 0) {
    startPrediction()
  }
}

// 查看详情
const viewDetails = (row: any) => {
  ElMessageBox.alert(
    `产品：${row.productName}\n预测出库量：${row.predictedQuantity}\n置信度：${row.confidence}%\n风险等级：${row.riskLevel}\n建议：${row.recommendation}`,
    '预测详情',
    {
      confirmButtonText: '确定'
    }
  )
}

// 获取置信度颜色
const getConfidenceColor = (confidence: number) => {
  if (confidence >= 90) return '#67C23A'
  if (confidence >= 70) return '#E6A23C'
  return '#F56C6C'
}

// 获取风险等级类型
const getRiskLevelType = (level: string) => {
  switch (level) {
    case '低': return 'success'
    case '中': return 'warning'
    case '高': return 'danger'
    default: return 'info'
  }
}

onMounted(() => {
  checkDataQuality()
})
</script>

<style scoped>
.outbound-prediction-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.subtitle {
  color: #909399;
  font-size: 14px;
}

.prediction-config,
.prediction-results,
.data-quality {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.config-form {
  margin-top: 20px;
}

.prediction-stats {
  margin-bottom: 30px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.prediction-charts {
  margin-bottom: 30px;
}

.chart-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.chart-container h4 {
  margin-bottom: 20px;
  color: #303133;
}

.chart {
  height: 300px;
}

.prediction-table h4 {
  margin-bottom: 20px;
  color: #303133;
}

.quality-stats {
  padding: 20px 0;
}

.quality-item {
  text-align: center;
  padding: 20px;
}

.quality-number {
  font-size: 24px;
  font-weight: bold;
  color: #67C23A;
  margin-bottom: 10px;
}

.quality-label {
  color: #909399;
  font-size: 14px;
}
</style> 